﻿package com.d4p.util
{
	import com.greensock.TweenMax;
	
	import flash.display.Sprite;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;

	public class SoundHandle extends Sprite
	{
		static private var _soundHandleInstance:SoundHandle;
		
		private var _bgmSound:Sound;
		private var _position:int;
		private var _soundTransform:SoundTransform;
		private var _currentVolume:int;
		
		public function SoundHandle(singletonEnforcer:SingletonEnforcer){}
		
		public static function getSoundInstance():SoundHandle
		{
			if(SoundHandle._soundHandleInstance == null){
				SoundHandle._soundHandleInstance = new SoundHandle(new SingletonEnforcer());	
			}
			return SoundHandle._soundHandleInstance;
		}
		
		//sound 최초 로드
		private var _soundChannel:SoundChannel;
		
		public function createSound($url:String, $firstVolume:int):void
		{
			if(_bgmSound == null){
				_bgmSound	   		= new Sound(new URLRequest($url));
				_soundChannel 		= _bgmSound.play(0, int.MAX_VALUE);
				
				_soundTransform		= new SoundTransform(0, 0);
				_soundChannel.soundTransform = _soundTransform
				
				if($firstVolume != 0){
					_playing = true;	
					volumeController  =$firstVolume;
				}else{
					_playing = false;
				}
				
			}
			
		}
		
		//soundPlay
		/**
			num=0  -->   overSound
		**/
		 
		private var _playing:Boolean;
		public function playSoundHandler($volume:int):void
		{
			//trace("play sound");
			if(!_playing){
				_soundChannel = _bgmSound.play(0, int.MAX_VALUE);
				_playing = true;
				_soundTransform		= new SoundTransform(0, 0);
				_soundChannel.soundTransform = _soundTransform;
				
				volumeController = $volume;
			}
		} 
		
		public function pauseSoundHandler():void
		{
			//trace("pause sound");
			if(_playing){
				//volumeController = 0;
				_soundChannel.soundTransform = _soundTransform;
				_soundChannel.stop();
				_playing = false;
			}
		}
		
		public function set volumeController($param:int):void
		{
			var $volume:Number = $param*0.34;
			TweenMax.to(_soundChannel, 0.4, {volume:$volume});
			
			//trace(">>>"+$volume);
		}
		
		
		private var _soundCurrentVol:int = 3;
		public function set soundCurrentVol($param:int):void
		{
			_soundCurrentVol = $param;
		}
		public function get soundCurrentVol():int
		{
			return _soundCurrentVol;
		}
		
		
	}
}

class SingletonEnforcer{}